package com.nl.controller.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.model.Response;
import com.nl.controller.common.util.ResponseUtil;
import com.nl.controller.web.bean.PDF.PdfReport;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.service.SmsReportTotalService;
import com.nl.controller.web.bean.SmsReportTotal;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.util.ExcelUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.apache.bcel.generic.IF_ACMPEQ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/smsReportTotal")
@Slf4j
public class SmsReportTotalController {
    @Autowired
    private SmsReportTotalService smsReportTotalService;

    @ApiOperation(value = "短信发送量统计分析", notes = "短信发送量统计分析")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "limit", value = "每页数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "way", value = "时间段查询方式", required = true, dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "发送起始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "发送结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "month", value = "发送的月份", required = true, dataType = "String"),
            @ApiImplicitParam(name = "counWay", value = "发送的月份", required = true, dataType = "String"),

    })
    @PostMapping("find")
    public Response find(
            HttpSession session,
            @RequestParam(value = "page", required = true) int page,
            @RequestParam(value = "limit", required = true) int limit,
            @RequestParam(value = "way", required = false) String way,//时间方式
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "month", required = false) String month,
            @RequestParam(value = "countWay", required = false) String countWay,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "countyId", required = false) String countyId,
            @RequestParam(value = "mgrType", required = false) String mgrType,
            @RequestParam(value = "mgrId", required = false) String mgrId,
            @RequestParam(value = "mgrName", required = false) String mgrName,
            @RequestParam(value = "regionId", required = false) String regionId,
            @RequestParam(value = "stationId", required = false) String stationId,
            @RequestParam(value = "year", required = false) String year,
            @RequestParam Map<String, Object> paramMap
    ) {
        //防止查询所有的数据
        if ("".equals(way) || way == null) {
            throw new SmsException("请选择查询条件，开始查询");
        } else {
            PageInfo<SmsReportTotal> pageInfo;
            SmsUsers smsUsers = (SmsUsers) session.getAttribute("user");
            pageInfo = smsReportTotalService.find(smsUsers, page, limit, month, way, startTime, endTime, countWay, cityId, mgrType, mgrId, mgrName, regionId, stationId, countyId, year);
            log.info("短信发送量统计参数：{}", paramMap.toString());
            log.debug("短信发送量统计返回数据：{}", pageInfo.getList().toString());
            return ResponseUtil.sucess(pageInfo.getList(), pageInfo.getTotal());
        }
    }

    @ApiOperation(value = "短信发送量统计分析导出", notes = "短信发送量统计分析")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "way", value = "时间段查询方式", required = true, dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "发送起始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "发送结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "month", value = "发送的月份", required = true, dataType = "String"),
            @ApiImplicitParam(name = "counWay", value = "发送的月份", required = true, dataType = "String"),

    })
    @GetMapping("download")
    public void download(
            HttpSession session,
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "way", required = false) String way,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "month", required = false) String month,
            @RequestParam(value = "countWay", required = false) String countWay,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "mgrType", required = false) String mgrType,
            @RequestParam(value = "mgrId", required = false) String mgrId,
            @RequestParam(value = "mgrName", required = false) String mgrName,
            @RequestParam(value = "regionId", required = false) String regionId,
            @RequestParam(value = "stationId", required = false) String stationId,
            @RequestParam(value = "countyId", required = false) String countyId,
            @RequestParam(value = "year", required = false) String year
    ) {
        //防止导出所有数据
        if ("".equals(way) || way == null) {
            throw new SmsException("查询条件不能为空");
        } else {
            SmsUsers smsUsers = (SmsUsers) session.getAttribute("user");
            //JSONArray ja = smsReportTotalService.download(smsUsers, way, month, startTime, endTime, countWay,cityId,mgrType,mgrId,mgrName,regionId,stationId,countyId,year);//获取业务数据集
            //获取业务数据集
            List<SmsReportTotal> reportTotals = smsReportTotalService.download2(smsUsers, way, month, startTime, endTime, countWay, cityId, mgrType, mgrId, mgrName, regionId, stationId, countyId, year);
            log.info("---" + reportTotals.size());
            Map<String, String> headMap = new LinkedHashMap<>();
            String title = "";
            String duty = smsUsers.getDuty();
            List<String> titleList = new ArrayList<>();
            String type = "";
            try {
                Thread.sleep(5000);
            }catch (Exception e){
                e.printStackTrace();
            }


            if ("city".equals(countWay)) {
                title = "短信统计表（按地市).pdf";
                titleList.add("地市");
                titleList.add("长短信发送量");
                titleList.add("长短信拆分后的数量");
                titleList.add("长短信占比");
                titleList.add("正常短信发送量");
                titleList.add("正常短信占比");
                titleList.add("总发送量");
                titleList.add("外地市短信发送量");
                titleList.add("外地市短信占比");
                titleList.add("外省短信发送量");
                titleList.add("外省短信占比");

                if ("0".equals(duty)) {
                    titleList.add("总费用(总发送量*0.03)");
                    type = "2";
                } else {
                    type = "1";
                }


            } else if ("mgr".equals(countWay)) {
                title = "短信统计表（按项目).pdf";
                titleList.add("地市");
                titleList.add("区县");
                titleList.add("项目名称");
                titleList.add("短信通道号");
                titleList.add("长短信发送量");
                titleList.add("长短信拆分后的数量");
                titleList.add("长短信占比");
                titleList.add("正常短信发送量");
                titleList.add("正常短信占比");
                titleList.add("总发送量");
                titleList.add("外地市短信发送量");
                titleList.add("外地市短信占比");
                titleList.add("外省短信发送量");
                titleList.add("外省短信占比");

                if ("0".equals(duty)) {
                    titleList.add("总费用(总发送量*0.03)");
                    type = "4";
                } else {
                    type = "3";
                }

            } else if ("type".equals(countWay)) {
                title = "短信统计表（按类型).pdf";
                titleList.add("地市");
                titleList.add("区县");
                titleList.add("项目类型");
                titleList.add("长短信发送量");
                titleList.add("长短信拆分后的数量");
                titleList.add("长短信占比");
                titleList.add("正常短信发送量");
                titleList.add("正常短信占比");
                titleList.add("总发送量");
                titleList.add("外地市短信发送量");
                titleList.add("外地市短信占比");
                titleList.add("外省短信发送量");
                titleList.add("外省短信占比");

                if ("0".equals(duty)) {
                    titleList.add("总费用(总发送量*0.03)");
                    type = "6";
                } else {
                    type = "5";
                }

            } else if ("content".equals(countWay)) {
                title = "短信统计表（按短信内容).pdf";

                titleList.add("地市");
                titleList.add("区县");
                titleList.add("项目名称");
                titleList.add("短信内容");
                titleList.add("长短信发送量");
                titleList.add("长短信拆分后的数量");
                titleList.add("长短信占比");
                titleList.add("正常短信发送量");
                titleList.add("正常短信占比");
                titleList.add("总发送量");
                titleList.add("外地市短信发送量");
                titleList.add("外地市短信占比");
                titleList.add("外省短信发送量");
                titleList.add("外省短信占比");

                if ("0".equals(duty)) {
                    titleList.add("总费用(总发送量*0.03)");
                    type = "8";
                } else {
                    type = "7";
                }


            } else if ("region".equals(countWay)) {
                title = "短信统计表（按区域).pdf";

                titleList.add("地市");
                titleList.add("区县");
                titleList.add("项目名称");
                titleList.add("区域名称");
                titleList.add("长短信发送量");
                titleList.add("长短信拆分后的数量");
                titleList.add("长短信占比");
                titleList.add("正常短信发送量");
                titleList.add("正常短信占比");
                titleList.add("总发送量");
                titleList.add("外地市短信发送量");
                titleList.add("外地市短信占比");
                titleList.add("外省短信发送量");
                titleList.add("外省短信占比");

                if ("0".equals(duty)) {
                    titleList.add("总费用(总发送量*0.03)");
                    type = "10";
                } else {
                    type = "9";
                }


            } else if ("Station".equals(countWay)) {
                title = "短信统计表（按基站).pdf";

                titleList.add("地市");
                titleList.add("区县");
                titleList.add("项目名称");
                titleList.add("区域名称");
                titleList.add("基站名称");
                titleList.add("长短信发送量");
                titleList.add("长短信拆分后的数量");
                titleList.add("长短信占比");
                titleList.add("正常短信发送量");
                titleList.add("正常短信占比");
                titleList.add("总发送量");
                titleList.add("外地市短信发送量");
                titleList.add("外地市短信占比");
                titleList.add("外省短信发送量");
                titleList.add("外省短信占比");

                if ("0".equals(duty)) {
                    titleList.add("总费用(总发送量*0.03)");
                    type = "12";
                } else {
                    type = "11";
                }

            } else if ("county".equals(countWay)) {
                title = "短信统计表（按区县).pdf";

                titleList.add("地市");
                titleList.add("区县");
                titleList.add("长短信发送量");
                titleList.add("长短信拆分后的数量");
                titleList.add("长短信占比");
                titleList.add("正常短信发送量");
                titleList.add("正常短信占比");
                titleList.add("总发送量");
                titleList.add("外地市短信发送量");
                titleList.add("外地市短信占比");
                titleList.add("外省短信发送量");
                titleList.add("外省短信占比");

                if ("0".equals(duty)) {
                    titleList.add("总费用(总发送量*0.03)");
                    type = "14";
                } else {
                    type = "13";
                }

            }
            new PdfReport().createPdfReport(title, type, titleList, reportTotals);
            goToDownload(request, response, title);
            log.info("---生成pdf成功---");
//            ExcelUtil.downloadExcelFile(title, headMap, ja, response,request);
//            ExcelUtil.downloadExcelFile(title, headMap, ja, response,request);
//            System.out.println("共" + ja.size() + "条数据,执行");
        }
    }

    /**
     * 下载
     *
     * @param request
     * @param response
     * @param fileName 下载文件的名称
     */
    private void goToDownload(HttpServletRequest request, HttpServletResponse response, String fileName) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-msdownload");
        try {
            String encodenickname = URLEncoder.encode(fileName, "UTF-8");//转Unicode不然ie会乱码
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(encodenickname.getBytes("UTF-8"), "ISO8859-1"));
            //这里注掉的代码是本地测试的
//            String path = request.getSession().getServletContext().getRealPath("/");
//            String ATTACH_PATH= AppConfig.getInstance().getProperty("attach.base","");
//            if (StringUtils.isNotEmpty(ATTACH_PATH)) {
//                path = ATTACH_PATH;
//            }
//            logger.debug("=path===" + path);
            File file = new File("D:\\欢迎名片报表文件.pdf");
            if (!file.exists()) {
                response.sendError(404, "File not found!");
                return;
            }
            long fileLength = file.length();
            response.setHeader("Content-Length", String.valueOf(fileLength));
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}





